package com.example.xgakj.newterminal.models;

import android.app.Activity;

import com.example.xgakj.mylibrary.mvp.utils.CommonUtil;
import com.example.xgakj.mylibrary.mvp.utils.ToastUtil;
import com.example.xgakj.newterminal.beans.ResultBean;
import com.google.gson.Gson;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.socks.library.KLog;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author Administrator
 * @date 2017-10-17
 */

public abstract class BaseJsonCallBack<T> extends AbsCallback<T>{
    private QMUITipDialog tipDialog;
    private Activity mActivity;

    public BaseJsonCallBack(Activity activity) {
        if (activity!=null){
            this.mActivity = activity;
            tipDialog = new QMUITipDialog.Builder(mActivity)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord("正在加载")
                    .create();
        }


    }


    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        if (tipDialog!=null){
            tipDialog.show();
            KLog.e(" tipDialog.show()");
        }

    }

    @Override
    public void onError(Response<T> response) {
        super.onError(response);
        if (mActivity!=null){
            ToastUtil.showShort(mActivity,"网络连接失败，请检查网络配置");
        }

        if (tipDialog!=null){
            tipDialog.dismiss();
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
        KLog.d("onFinish");
        if (tipDialog!=null){
            tipDialog.dismiss();
            KLog.e(" tipDialog.dismiss()");
        }
    }

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        if (response.body()==null){
            return null;
        }
        T data=null;
        String stringBody = response.body().string();
        KLog.e(stringBody);
        Gson gson=new Gson();
        ResultBean resultBean=gson.fromJson(stringBody,ResultBean.class);
        KLog.e(resultBean.toString());
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType){
            ParameterizedType parameterizedType= (ParameterizedType) type;
            Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0];
            if (actualTypeArgument ==ResultBean.class){
                KLog.e("是ResultB");
                data= (T) resultBean;
                return data;
            }else {
                KLog.e("不是ResultB");
                String obj=resultBean.getObj();
                if (!CommonUtil.isNull(obj)){
                    data=gson.fromJson(obj, actualTypeArgument);
                }
            }
        }


        return data;
    }
}
